# Filename: jit-mda-transfer-image.sh 
# Usage: jit-mda-configure-drbd.sh <imagename> <primaryIp> <backupIp>
# Example: jit-mda-configure-drbd.sh vm01 10.0.0.1 10.0.0.2
#
# Prepares the VM configuration file to interact with DRBD,
# builds a .RES file containing hosts data for DRBD and
# creates a metadata LVM for DRBD.
#
# Notes:
# 1) This script is also made to fix a xen-tools bug, changing
# any "SDA" disk references to "XVDA".
#
# 2) The DRBD ports and device "minor numbers" on this script are
# hard-coded. On future versions, these numbers will be parameters,
# allowing for many failover protected VMs on a single pair of hosts.


imagename=$1
primaryIp=$2
backupIp=$3
CFGPATH=/etc/xen
DRBDPATH=/etc/drbd.d
drbdfile=$DRBDPATH/${imagename}.res
drbdDev=/dev/drbd3
drbdPort=7792
priHostname=''
bakHostname=''

echo `date +%H:%M:%S` Starting Script $0 $*
if [ -z "$imagename" ]; then
	echo "Usage: $0 <imagename> <primaryIp> <backupIp>"
else
	priHostname=`ssh root@$primaryIp 'hostname'`
	bakHostname=`ssh root@$backupIp 'hostname'`
	
	# Fixing the Xen-Tools bug on CFG
	sed -i -e "s/sda/xvda/g" $CFGPATH/$imagename.cfg
	# Pointing disks to DRBD
	sed -i -e "s|/dev.*,xvda|$drbdDev,xvda|g" $CFGPATH/$imagename.cfg

	# Building DRBD's resource file
	echo "resource $imagename { " > $drbdfile
	echo "  device $drbdDev;" >> $drbdfile
	echo "  disk /dev/vg_datastore/${imagename}-disk;" >> $drbdfile
	echo "  meta-disk /dev/vg_datastore/${imagename}-metadata[0];" >> $drbdfile
	echo "  on $priHostname {" >> $drbdfile
	echo "          address $primaryIp:$drbdPort;" >> $drbdfile
	echo "  }" >> $drbdfile
	echo "  on $bakHostname {" >> $drbdfile
	echo "          address $backupIp:$drbdPort;" >> $drbdfile
	echo "  }" >> $drbdfile
	echo "}" >> $drbdfile

	# Creating a LVM for DRBD metadata according to above .RES file
	lvcreate  -L 200 vg_datastore -n ${imagename}-metadata
	drbdadm -- --force create-md $imagename
	drbdadm up $imagename
fi
echo `date +%H:%M:%S` Finishing Script $0
exit 0
